from __future__ import print_function
import os
import subprocess

class Analyzer:
    def __init__(self, asserting):
        self.asserting = asserting
        self.stats = []
        self.col = ["16", "3", "4", "10", "12", "7", "7", "8"]
    
    def accumulate(self, inPath, outPath, M, W, assertion, adapt = False):
        file = os.path.split(inPath)[1]
        inSize = os.path.getsize(inPath)
        outSize = os.path.getsize(outPath)
        BR = 8 * float(outSize) / inSize
        CR = float(inSize) / outSize
        if self.asserting:
            self.stats.append([file, W, M, inSize, outSize, BR, CR, assertion, adapt])
        else:
            self.stats.append([file, W, M, inSize, outSize, BR, CR, adapt]) 
        
    def assertCoding(self, inPath, outPath, delete=True):
        cmd = ["md5sum", inPath]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        md5in = p.stdout.read().split(" ")[0]
        
        cmd = ["md5sum", outPath]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        md5out = p.stdout.read().split(" ")[0]
        if delete:
            os.remove(outPath)

        return md5in == md5out
    
    def printStats(self, header = True):
        col = self.col
        if header:
            print(("{:>" + col[0] + "}, "
                  "{:>" + col[1] + "}, " 
                  "{:>" + col[2] + "}, " 
                  "{:>" + col[3] + "}, " 
                  "{:>" + col[4] + "}, " 
                  "{:>" + col[5] + "}, " 
                  "{:>" + col[6] + "}").format("File", "W", "M",
                                               "Raw", "Compressed",
                                               "BR", "CR"),
                  end="")
            if self.asserting:
                print((", {:>" + col[7] + "}").format("Assert"), end="")
            print()
        
        for row in self.stats:
            self.printRow(row = row)
            
    def printRow(self, row = None):
        col = self.col
        if row is None:
            row = self.stats[-1]
        
        print(("{:>" + col[0] + "}, ").format(row[0]), end="")
        print(("{:>" + col[1] + "}, ").format(row[1]), end="")
        if row[-1] == True:
            print(("{:>" + col[2] + "}, ").format("*" + str(row[2])), end="")
        else:  
            print(("{:>" + col[2] + "}, ").format(row[2]), end="")  
        print(("{:>" + col[3] + "}, ").format(row[3]), end="")  
        print(("{:>" + col[4] + "}, ").format(row[4]), end="")      
        print(("{:>" + col[5] + ".3f}, ").format(row[5]), end="")  
        print(("{:>" + col[6] + ".3f}").format(row[6]), end="")  
        if self.asserting:
            if row[7]:
                print((", {:>" + col[7] + "}").format("pass"), end="")
            else:
                print((", {:>" + col[7] + "}").format("fail"), end="")
        print()
    
    
def getAnalyzer(asserting=False):
    return Analyzer(asserting)
        
    
    
